package cn.south.campus.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2022/5/7 14:09
 */
public class DateUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(DateUtil.class);

    public static LocalDateTime parseString(String dateStr) {
        if (dateStr == null) {
            return null;
        }
        return LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public static String format(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            return null;
        }
        return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public static String getTimeAgo(LocalDateTime givenTime) {
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 计算时间差
        long secondsDiff = ChronoUnit.SECONDS.between(givenTime, currentTime);
        long minutesDiff = ChronoUnit.MINUTES.between(givenTime, currentTime);
        if (secondsDiff < 60) {
            return secondsDiff + "秒前";
        }
        // 根据时间差返回相应的描述
        if (minutesDiff < 60) {
            return minutesDiff + "分钟前";
        } else if (minutesDiff < 24 * 60) {
            return minutesDiff / 60 + "小时前";
        } else if (minutesDiff < 30 * 24 * 60) {
            return minutesDiff / 60 / 24 + "天前";
        } else if (minutesDiff < 365 * 24 * 60) {
            return minutesDiff / 60 / 24 / 30 + "月前";
        } else {
            return minutesDiff / 60 / 24 / 365 + "年前";
        }
    }

    public static String formatNowDate() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    }

    public static String formatTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    }

    public static String datePath() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
    }

    public static String getYear(LocalDateTime now) {
        return now.getYear() + "";
    }

    public static String getMonth(LocalDateTime now) {
        return now.getMonthValue() + "";
    }

    public static String getDate(LocalDateTime now) {
        return now.getDayOfMonth() + "";
    }
}
